package org.mca.mcaweb.converter;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter("genericConverter")
public class GenericConverter implements Converter {

	public Object getAsObject(FacesContext ctx, UIComponent comp, String value) {
		if (value != null) {
			return this.getAttributesFrom(comp).get(value);
		}
		return null;
	}

	public String getAsString(FacesContext ctx, UIComponent comp, Object value) {
		if (value != null && !"".equals(value)) {
			String pk = null;
			this.addAttribute(comp, value);
			pk = value.toString();
			if (pk != null) {
				return String.valueOf(pk);
			}
		}
		return (String) value;
	}

	protected Map<String, Object> getAttributesFrom(UIComponent component) {
		return component.getAttributes();
	}

	protected void addAttribute(UIComponent component, Object object) {
		String key = object.toString();
		this.getAttributesFrom(component).put(key, object);
	}
}
